package com.cocostudio.erpapp;

import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.FragmentManager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

public class CustomDialogFragment extends DialogFragment {

    public static void show(FragmentManager fragmentManager, CustomDialogInfo info) {
        CustomDialogFragment fragment = new CustomDialogFragment(info);
        fragmentManager.beginTransaction().add(fragment, "alert_dialog").commit();
    }

    public static void dismiss(FragmentManager fragmentManager) {
        fragmentManager.beginTransaction().remove(fragmentManager.findFragmentByTag("alert_dialog")).commit();
    }

    CustomDialogInfo i;

    CustomDialogFragment(CustomDialogInfo info) {
        i = info;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        Builder builder = new Builder(getActivity());
        if (i.icon > 0) {
            builder.setIcon(i.icon);
        }
        if (i.title > 0) {
            builder.setTitle(i.title);
        }
        if (i.viewRes > 0 || i.view != null) {
            builder.setView(i.view == null ? LayoutInflater.from(getActivity()).inflate(i.viewRes, null) : i.view);
        } else {
            if (i.message > 0) {
                LayoutInflater inflater = LayoutInflater.from(getActivity());
                TextView textView = (TextView) inflater.inflate(R.layout.text_alert_dialog, null);
                textView.setText(i.message);
                builder.setView(textView);
            }
        }
        builder.setPositiveButton(i.positiveButtonText, i.positiveButtonListener);
        if (i.showNegativeButton) {
            builder.setNegativeButton(i.negativeButtonText, i.negativeButtonListener);
        }
        return builder.create();
    }

    public static class CustomDialogInfo {
        public int title = -1;
        public int message = -1;
        public int viewRes = -1;
        public View view = null;
        public int icon = android.R.drawable.ic_dialog_alert;
        public int positiveButtonText = android.R.string.ok;
        public OnClickListener positiveButtonListener;
        public boolean showNegativeButton = false;
        public int negativeButtonText = android.R.string.cancel;
        public OnClickListener negativeButtonListener;

    }
}
